package com.example.dbcms.controller.user;

import com.example.dbcms.annotation.Log;
import com.example.dbcms.domain.Repair;
import com.example.dbcms.domain.User;
import com.example.dbcms.service.RepairService;
import com.example.dbcms.service.UserService;
import com.example.dbcms.utils.DateUtil;
import com.example.dbcms.utils.ResultVoUtil;
import com.example.dbcms.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
@Api("普通用户维修信息路由")
public class UserRepairController {

    @Autowired
    private UserService userService;

    @Autowired
    private RepairService repairService;
    /**
     * 跳转到用户对应维修记录页面
     * @return
     */
    @GetMapping("/repair")
    @ApiOperation("跳转到用户对应维修记录页面")
    @Log(type="跳转到用户对应维修记录页面")
    public String repairInfo(Repair repair, ModelMap modelMap){
        String userAccount = (String) SecurityUtils.getSubject().getPrincipal();//获得账号
        User user = userService.getUserByUserAccount(userAccount);
        repair.setBuildingNo(user.getBuildingNo());
        repair.setRoomNo(user.getRoomNo());
        PageInfo<Repair> repairPageInfo = repairService.selectAllRepair(repair);
        modelMap.put("repairInfoList",repairPageInfo.getList());
        modelMap.put("repairInfo",repair);
        modelMap.put("pageInfo",repairPageInfo);
        return "user/repair/index";
    }

    /**
     * 用户新增报修记录
     * @return
     */
    @GetMapping("/addRepair")
    @ApiOperation("用户新增报修记录")
    @Log(type="用户新增报修记录")
    public String addRepair(){
        return "user/repair/add";
    }

    /**
     * 新增维修信息
     * @param repair
     * @return
     */
    @PostMapping("/addRepair")
    @ResponseBody
    @ApiOperation("新增维修信息")
    @Log(type="新增维修信息")
    public ResultVo addRepairToDb(Repair repair){
        if(repair.getDetails().length()==1){
            return ResultVoUtil.error("请填写报修信息");
        }
        String userAccount = (String) SecurityUtils.getSubject().getPrincipal();//获得账号
        User user = userService.getUserByUserAccount(userAccount);
        repair.setBuildingNo(user.getBuildingNo());
        repair.setRoomNo(user.getRoomNo());
        repair.setApplicationDate(DateUtil.getCurrentDate());
        repair.setStatus("申请中");
        System.out.println(repair);
        int result = repairService.addRepair(repair);
        if(result == 1){
            return ResultVoUtil.success("添加成功");
        }
        return ResultVoUtil.error("添加失败");
    }
}
